package com.itaming.lycheeframework.mybatisflex.autofill;

import com.itaming.lycheeframework.common.constant.FrameworkConstant;
import com.itaming.lycheeframework.mybatisflex.base.BaseEntity;
import com.mybatisflex.annotation.InsertListener;
import lombok.RequiredArgsConstructor;

import java.time.LocalDateTime;

/**
 * BaseEntity插入监听器
 *
 * @author A.Ming
 */
@RequiredArgsConstructor
public class BaseEntityInsertListener implements InsertListener {

    /**
     * 自动填充提供者
     */
    private final AutoFillProvider autoFillProvider;

    @Override
    public void onInsert(Object o) {
        // 转换实体
        BaseEntity entity = (BaseEntity) o;

        // 获取填充值
        Long currentUserId = autoFillProvider.getCurrentUserId();
        LocalDateTime now = LocalDateTime.now();

        // 设置填充值
        if (entity.getCreateUser() == null) {
            entity.setCreateUser(currentUserId);
        }
        if (entity.getCreateTime() == null) {
            entity.setCreateTime(now);
        }
        if (entity.getUpdateUser() == null) {
            entity.setUpdateUser(currentUserId);
        }
        if (entity.getUpdateTime() == null) {
            entity.setUpdateTime(now);
        }
        // 逻辑删除字段建议在数据库层面设置默认值，此处仅作为补充和兜底
        entity.setIsDeleted(FrameworkConstant.NOT_DELETED);
    }

}
